package com.bsg.upm.service;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.bsg.upm.constant.TaskDictTypeConstants;
import com.bsg.upm.dto.TaskDto;
import com.bsg.upm.entity.TaskEntity;
import com.bsg.upm.exception.APIException;
import com.bsg.upm.http.RespJson;
import com.bsg.upm.http.RespJsonFactory;
import com.bsg.upm.util.DateUtils;

/**
 * 任务管理业务处理类
 * 
 * @author HCK
 *
 */
@Service
public class TaskService extends BaseService {

	/**
	 * 任务查询
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	public RespJson list(Map<String, Object> paramMap) throws APIException {
		try {
			// 结果集
			JSONArray results = new JSONArray();

			// 获取指定条件的任务
			List<TaskEntity> tasks = taskDao.list(paramMap);

			for (TaskEntity task : tasks) {
				// 构建任务展示对象
				TaskDto taskDto = buildShowDto(task, false);
				results.add(taskDto);
			}

			return RespJsonFactory.buildOK(results);
		} catch (Exception e) {
			logger.error("任务查询异常", e);
			throw new APIException("任务查询异常:" + e.getMessage());
		}
	}

	/**
	 * 构建任务展示对象
	 * 
	 * @param task
	 *            任务对象
	 * @param showDetail
	 *            是否展示详情
	 * @return 任务展示对象
	 */
	private TaskDto buildShowDto(TaskEntity task, boolean showDetail) {
		TaskDto taskDto = new TaskDto();
		taskDto.setId(task.getId());
		taskDto.setSiteId(task.getSite().getId());
		taskDto.setSiteName(task.getSite().getName());
		taskDto.setObjId(task.getObjId());
		taskDto.setObjType(dictTypeCache.getTextFromCache(TaskDictTypeConstants.TASK_OBJ_TYPE, task.getObjType()));
		taskDto.setObjName(task.getObjName());
		taskDto.setActionType(
				dictTypeCache.getTextFromCache(TaskDictTypeConstants.TASK_ACTION_TYPE, task.getActionType()));
		taskDto.setStartDateTime(DateUtils.dateTimeToString(task.getStartDateTime()));
		taskDto.setEndDateTime(DateUtils.dateTimeToString(task.getEndDateTime()));
		taskDto.setStatus(task.getStatus());
		taskDto.setStatusText(dictTypeCache.getTextFromCache(TaskDictTypeConstants.TASK_STATUS, task.getStatus()));
		taskDto.setMsg(task.getMsg());
		taskDto.setOwner(task.getOwner());
		return taskDto;
	}
}
